'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 战斗
 * @author sundbcn@gmail.com (sun debing)
 */

var moment = require('moment');
var async = require('async');
var modelUtil = require('../util/modelUtil');
var mongoConnector = require('../libs/mongodb/mongoConnector');
/* jshint unused:false */
var battleSchema = require('../schemas/battleSchema');
var Battle = mongoConnector().model('Battle');
var rivalService = require('../services/rivalService');
var constantUtil = require('../util/constantUtil');
var roleModel = require('../models/roleModel');

/**
 * 根据角色id获取掠夺数据
 */
module.exports.getByRoleId = function (role_id, cb) {
    modelUtil.getByRoleId(Battle, role_id, function (err, battle_model) {
        if (!!err) {
            console.error(err);
            return cb(err);
        }

        cb(null, battle_model);
    });
};

/**
 * 获取角色列表
 */
module.exports.findWhere = function (where, cb) {
    Battle.find(where, cb);
};

/**
 * 获取当前玩家排名
 */
module.exports.getCupRankByRoleId = function (role_id, cup_num, cb) {
    var count;
    var other_count;
    async.series(
        [
            function (cb) {
                Battle.where('cup')
                    .gt(cup_num)
                    .count(
                        function (err, num) {
                            count = num;
                            cb();
                        });
            },
            function (cb) {
                Battle.where('cup')
                    .equals(cup_num)
                    .where('role_id')
                    .gte(role_id)
                    .count(
                        function (err, num) {
                            other_count = num;
                            cb();
                        });
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
            }
            cb(null, count + other_count);
        }
    );
};

/**
 * 获取玩家奖杯数前50名
 */
module.exports.getCupTopFifty = function (cb) {
    Battle.find({})
        .sort('-cup')
        .sort('-role_id')
        .limit(50)
        .select('role_id cup noble')
        .exec(cb);
};
